import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,parseToChart} from '../apis/core-util'
import traceDetail from '../apis/traceDetail'

function parseTrace(data){
  return _.extend({},data,{
		params:JSON.parse(data.params),
		trace:data.trace.split('\n'),
		responseBody:data.responseBody
	});
}

export default class TraceGroupScope extends Scope {
  constructor(props){
    super();
    this.domainId = props.routeParams.domainId
    this.urlId = props.routeParams.urlId
    this.statusCode = props.routeParams.statusCode
    this.traceOffset = 0
    this.traces = [];
    this.realTraces = [];
    this.$state = {
      trace:null,
      detail:null,
      chart:{
        loading:true
      },
      pie0:{
        loading:true
      },
      pie1:{
        loading:true
      },
      pie2:{
        loading:true
      }
    }
    this.traceApi = coreApi({
      urlName:'httperrorsimilar',
      limit:200,
      order:'101',
      viewKey:'http_similar_error_count',
      domainId:this.domainId,
      urlId:this.urlId,
      statusCode:this.statusCode
    },TimeStore.getValue);
    this.pie0Api = coreApi({
      urlName:'errorrate',
      viewKey:'error_count',
      size:1,
      classify:'carries',
      order:sortMap['error_count'],
      domainId:this.domainId,
      urlId:this.urlId,
      statusCode:this.statusCode
    },TimeStore.getValue);
    this.pie1Api = coreApi({
      urlName:'errorrate',
      viewKey:'error_count',
      size:1,
      classify:'nettype',
      order:sortMap['error_count'],
      domainId:this.domainId,
      urlId:this.urlId,
      statusCode:this.statusCode
    },TimeStore.getValue);
    this.pie2Api = coreApi({
      urlName:'errorrate',
      viewKey:'error_count',
      size:1,
      classify:'region',
      order:sortMap['error_count'],
      domainId:this.domainId,
      urlId:this.urlId,
      statusCode:this.statusCode
    },TimeStore.getValue);
    this.affectedApi = coreApi({
      urlName:'httperrorsimilar',
      limit:200,
      size: 1,
      order:'101',
      viewKey:'http_similar_error_count',
      domainId:this.domainId,
      urlId:this.urlId,
      statusCode:this.statusCode
    },TimeStore.getValue);
    // traceDetail({
    //   id:this.traceId,
    //   urlName:'httperrortracedetail'
    // })
  }
  fetch(){
    var _this = this
    this.traceApi.fetch().then(function(data,params){
      _this.$state.trace = _.extend({},data.result[0].key,data.result[0].combData)
      _this.$state.chart = {
        data:parseToChart(data,params)
      }
      _this.showDetail(0)
    },function(err){
      _this.$state.chart = {
        error:err
      }
    },function(params){
      _this.$state.chart = {
        loading:true,
        params:params
      }
    }).then(() => {
      this.affectedApi.fetch().then((data) => {
        this.$state.trace.affected = data.result[0].combData.affected
      }).always(function(){
        _this.emit();
      })
    });

    this.pie0Api.fetch().then(function(data,params){
      _this.$state.pie0 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.pie0 = {
        error:err
      }
    },function(params){
      _this.$state.pie0 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
    this.pie1Api.fetch().then(function(data,params){
      _this.$state.pie1 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.pie1 = {
        error:err
      }
    },function(params){
      _this.$state.pie1 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
    this.pie2Api.fetch().then(function(data,params){
      _this.$state.pie2 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.pie2 = {
        error:err
      }
    },function(params){
      _this.$state.pie2 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
  }
  showDetail(offset){
    var _this = this
    var realOffset = this.realTraces.length;
    if(offset!==undefined){
      if(offset<0||offset>this.$state.trace.count - 1){
        return ;
      }
      this.traceOffset = offset;
    }
    if(this.traces[this.traceOffset]){
      this.$state.detail = this.traces[this.traceOffset];
      this.emit();
    }else{
      coreApi({
        urlName:'http_errortrace_detail_data',
        crashNameId:this.crashtraceId,
        domainId:this.domainId,
        urlId:this.urlId,
        statusCode:this.statusCode,
        offset:realOffset
      },TimeStore.getValue).fetch().then(function(trace,params){
        _this.$state.trace.url = trace.url;
        var parsedTrace = parseTrace(trace);
        _this.realTraces[realOffset] = parsedTrace
        _.chain(trace.count).range().each(function(v){
          _this.traces.push(parsedTrace)
        })
        _this.$state.detail = _this.traces[_this.traceOffset];
        _this.emit();
      })
    }
  }
  $unload(){
  }
  $load(){
    var _this = this
    this.fetch();

  }
}
function parseTrace(data){
  return _.extend({},data,{
		params:JSON.parse(data.params),
		trace:data.trace.split('\n'),
		responseBody:data.responseBody,
    httpRequestHeader:data.httpRequestHeader?data.httpRequestHeader.split('\n').filter((p) => p).map((p) => p.split(':')):[],
    httpResponseHeader:data.httpResponseHeader?data.httpResponseHeader.split('\n').filter((p) => p).map((p) => p.split(':')):[]
	});
}
